package cn.com.zp.util.base;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public class SecurityUtils {

	public static String md5s(String plainText) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(plainText.getBytes());
			byte b[] = md.digest();

			int i;

			StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}
//			System.out.println("原字符串: " + plainText);
//			System.out.println("32位加密: " + buf.toString());// 32位的加密
//			System.out.println("16位加密: " + buf.toString().substring(8, 24));// 16位的加密
			return buf.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 将信息按指定的算法加密
	 * 
	 * @param str
	 *            要加密的字符串
	 * @param digestType
	 *            加密类型，选择MD5或SHA-1
	 * @return 加密之后的内容
	 */
	public static String digestString(String str, String digestType) {
		MessageDigest md;
		String message = "";
		try {
			md = MessageDigest.getInstance(digestType);
			md.update(str.getBytes());
			message = StringUtils.byteToHex(md.digest());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return message;
	}

	public static void main(String agrs[]) {
		System.out.println(SecurityUtils.md5s("abcdefg"));
	}

}